package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

@WebFilter(filterName = "EncodeFilter",urlPatterns = "/*")
public class EncodeFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //设置请求的字符编码
        req.setCharacterEncoding("utf-8");
        //设置回应的字符编码
        resp.setCharacterEncoding("utf-8");
        // 添加日志
        String method = req.getParameter("method");
        HttpServletRequest httpServletRequest = (HttpServletRequest) req;
        Object username = httpServletRequest.getSession().getAttribute("username");
        if (method != null) {
            System.out.println("日志：用户 " + username + ":" + new Date() + "，执行了" + method + "方法。");
        }
        //放行
        chain.doFilter(req,resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
